import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Select,
  Space,
  DatePicker,
  message,
  Table,
  Tag,
  Image,
  Modal,
} from 'antd'
import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import { Link } from 'react-router-dom'
import { artStatus } from 'api/constant'
import { delArticleByIdAPI, getArticleAPI, getChannelsAPI } from 'api/content'
import defaultImg from 'assets/error.png'
import { formatDate } from 'utils'
import dayjs from 'dayjs'
import ArtChannel from 'components/ArtChannel'
const { Option } = Select
const { RangePicker } = DatePicker
const { confirm } = Modal
export default class Content extends Component {
  state = {
    channels: [],
    params: {
      page: 1,
      per_page: 10,
    },
    results: [],
    total: 0,
    isLoading: false,
  }
  componentDidMount() {
    this.getChannels()
    this.getAricles(this.state.params)
  }

  // 获取频道列表
  getChannels = async () => {
    const {
      data: { channels },
    } = await getChannelsAPI()
    this.setState({ channels })
  }

  // 获取文章列表
  getAricles = async (params) => {
    this.setState({ isLoading: true })
    const res = await getArticleAPI(params)
    this.setState({
      results: res.data.results,
      total: res.data.total_count,
      isLoading: false,
    })
  }

  // 表单提交筛选
  onFinish = ({ channel_id, status, date }) => {
    let begin_pubdate = null
    let end_pubdate = null
    if (date) {
      begin_pubdate = date[0].startOf('day').format('YYYY-MM-DD HH:mm:ss')
      end_pubdate = date[1].startOf('day').format('YYYY-MM-DD HH:mm:ss')
    }

    const { params } = this.state
    this.setState(
      {
        params: { ...params, channel_id, status, begin_pubdate, end_pubdate },
      },
      () => {
        console.log(this.state.params)
        this.getAricles(this.state.params)
      }
    )
  }

  // 页码变化
  pageChange = (page, per_page) => {
    const { params, results } = this.state
    this.setState(
      { params: { ...params, page, per_page }, results: [] },
      () => {
        this.getAricles(this.state.params)
      }
    )
  }

  // 删除
  delete = async (id) => {
    const { results, params } = this.state
    confirm({
      title: '删除文章',
      icon: <ExclamationCircleOutlined />,
      content: '确认删除这一项吗',
      onOk: async () => {
        await delArticleByIdAPI(id)
        message.success('删除成功')
        if (results.length === 1 && params.page !== 1) {
          this.setState({ params: { ...params, page: params.page - 1 } })
        }
        this.getAricles(this.state.params)
      },
      onCancel() {},
    })
  }

  // table表格的每一行
  columns = [
    {
      title: '封面',
      dataIndex: ['cover'],
      render: (cover) =>
        cover.type ? (
          <Image
            src={cover.images[0]}
            style={{ width: 200, height: 150 }}
            fallback={defaultImg}
          ></Image>
        ) : (
          <img src={defaultImg} style={{ width: 200, height: 150 }} />
        ),
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: '300px',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (text) => {
        const obj = artStatus.find((item) => item.id === text)
        return <Tag color={obj.color}>{obj.name}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      width: '200px',
      align: 'center',
      render: (text, row) => (
        <Space size="middle">
          <Link to={`/home/publicArt/${row.id}`}>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
            ></Button>
          </Link>
          <Button
            type="danger"
            shape="circle"
            onClick={() => this.delete(row.id)}
            icon={<DeleteOutlined />}
          ></Button>
        </Space>
      ),
    },
  ]

  render() {
    const { results, total, isLoading } = this.state
    return (
      <div className="articleList">
        {/* 筛选条件 */}
        <Card
          title={
            <Breadcrumb>
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>内容管理</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form onFinish={this.onFinish} initialValues={{ status: undefined }}>
            <Form.Item label="状态" name="status">
              <Radio.Group>
                {artStatus.map((item) => (
                  <Radio key={item.name} value={item.id}>
                    {item.name}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>
            <Form.Item label="频道" name="channel_id">
              <ArtChannel></ArtChannel>
            </Form.Item>
            <Form.Item label="日期" name="date">
              <RangePicker />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" onClick={this.onClick}>
                筛选
              </Button>
            </Form.Item>
          </Form>
        </Card>
        {/* 筛选表格 */}
        <Card title={`根据筛选条件共查询到${total}条数据`}>
          <Table
            columns={this.columns}
            dataSource={results}
            rowKey="id"
            loading={isLoading}
            pagination={{
              position: ['bottomCenter'],
              total,
              showTotal: () => '总数 ' + total,
              hideOnSinglePage: true,
              onChange: this.pageChange,
            }}
          />
        </Card>
      </div>
    )
  }
}
